package edu.towson.cosc.cosc455.mlam4.compiler;
import edu.towson.cosc.cosc455.interfaces.LexicalAnalyzer;

public class MyLexicalAnalyzer implements LexicalAnalyzer{
	char currentChar;
	String nextChar = "";
	String nextToken = "";
	int position = 0;
	String currentCharacter = "";
	
	//gets next token in file
	public void getNextToken() {
		getCharacter();
		while(isSpace(currentCharacter)){
				getCharacter();
		}
		if(isHash(currentCharacter)){
			processTag();
			if(!lookupToken()){
				System.err.println("ERROR! Token" + MyCompiler.token + "is Invalid");
				System.exit(0);
			}
		}
		else
			processText();
	}
	//gets next character in file
	public void getCharacter() {
		currentChar = (MyCompiler.lolFile.charAt(position));
		currentCharacter = currentChar + "";
		position++;
		
	}
	// adds character to nextchar variable
	public void addCharacter() {
		currentChar = MyCompiler.lolFile.charAt(position);
		nextChar = currentChar + "";
		position++;
	}

	
	//checks to see if there is a space
	public boolean isSpace(String c) {
		if (c.equals(" ") || c.equals("\t") || c.equals("\r"))
			return true;
		else
			return false;
	}
	
	//checks to see if there is a # sign
	public boolean isHash(String c){
		if(c.equals("#")){
			return true;
		}
		else 
			return false;
	}
	
	//looks up the current token
	public boolean lookupToken() {
		for(int i =0; i < (MyCompiler.validTokens).size();i++){
			if((MyCompiler.token).equalsIgnoreCase(MyCompiler.validTokens.get(i))){
				return true;
			}
		}
		return false;
	}
	
	
	public void processTag(){
		MyCompiler.token = currentCharacter;
		addCharacter();
		while(!isSpace(nextCharacter) && !isHash(nextCharacter)){
			MyCompiler.token = MyCompiler.token + nextCharacter;
			addCharacter();
		}
		if(!lookupToken()){
			processMutipleTags();
			if(!lookupToken()){
				processMutipleTags();
			}
		}
			
	}
	//used if multiple tags are part of a process
	public void processMutipleTags(){
		MyCompiler.token+=nextCharacter;
		addCharacter();
		while (!isSpace(nextCharacter) && !isHash(nextCharacter)){
			MyCompiler.token+=nextCharacter;
			addCharacter();
		}
	}
	
	
	//used to process text
    public void processText(){
        MyCompiler.token = currentCharacter;
        addCharacter();
        while (!isHash(nextCharacter)){
                MyCompiler.token += nextCharacter;
                addCharacter();
        }
        if (isHash(nextCharacter)){
                position--;
        }
    }
    
    
    //checks to see if the end of the file as been reached
	public boolean fileEnd(){
			while(position<MyCompiler.lolFile.length()){
					addCharacter();
					if(!isSpace(nextCharacter)){
						return false;
					}
			}
			return true;
	}
	
}

